<?php

namespace App\Imports;

use App\Models\Question;
use Carbon\Carbon;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Collection;
use Illuminate\Validation\Rule;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithBatchInserts;
use Maatwebsite\Excel\Concerns\WithChunkReading;
use Maatwebsite\Excel\Concerns\WithStartRow;
use Maatwebsite\Excel\Concerns\WithValidation;

class QuestionImport implements ToCollection, WithStartRow, WithChunkReading, WithBatchInserts, WithValidation
{
    protected $start = 2;

    protected $chunk = 100;

    protected $batch = 100;

    /**
     * @param Collection $collection
     * @return mixed
     */
    public function collection(Collection $collection)
    {
        $questions = [];

        // 移出html标签
        $timer = Carbon::now()->toDateTimeString();
        foreach ($collection as $key => $item) {
            $questions[$key]['status'] = 0;
            $questions[$key]['user_id'] = auth('api')->id();
            $questions[$key]['category_id'] =  $item[0];
            $questions[$key]['type'] = $item[1];
            $questions[$key]['title'] = substr(trim(strip_tags($item[2])),0,254);
            $questions[$key]['content'] = $item[2];
            $questions[$key]['answer'] = json_encode(json_decode($item[3], true));
            $questions[$key]['success_answer'] = $item[4];
            $questions[$key]['level'] = $item[6];
            $questions[$key]['fraction'] = $item[5];
            $questions[$key]['analysis'] = $item[7];
            $questions[$key]['created_at'] = $timer;
            $questions[$key]['updated_at'] = $timer;
        }
        Question::insert($questions);
    }

    /**
     * @return array
     */
    public function rules(): array
    {
        return [
            '1' => ['required', Rule::in(Question::TYPE)],
            '0' => ['bail', 'required', 'exists:categories,id,category_group_id,4'],
            '5' => ['required', 'between:0,100', 'integer'],
            '6' => ['sometimes', 'required', 'between:0,5', 'integer'],
            '7' => 'sometimes|required'
        ];
    }

    /**
     * 从第几行开始
     *
     * @return int
     */
    public function startRow(): int
    {
        return $this->start;
    }

    /**
     * @return int
     */
    public function chunkSize(): int
    {
        return $this->chunk;
    }

    /**
     * @return int
     */
    public function batchSize(): int
    {
        return $this->batch;
    }
}
